package com.wj.controller;

import com.wj.domain.vo.BookVO;
import com.wj.service.BookCacheService;
import com.wj.service.BookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @description: 手动执行任务
 * @author: wj
 * @create: 2022/2/14 13:42
 */
@RestController
@Slf4j
@Api(tags = "小说手动任务管理器")
public class BookHandler {

    @Resource
    private BookService bookService;

    @Resource
    private BookCacheService bookCacheService;

    @GetMapping("/update/book")
    @ResponseBody
    @ApiOperation("更新所有小说")
    public String updateFiction(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        log.info("开始更新小说"+sdf.format(now));
        //获取所有小说
        List<BookVO> list=bookService.getBookList();
        //循环更新小说
        for (BookVO bookVO:list){
            bookService.updateBook(bookVO.getId(),bookVO.getBookUrl());
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                log.info("线程休眠异常");
                e.printStackTrace();
            }
        }
        Date date = new Date();
        log.info("更新完成，"+sdf.format(date));
        return "执行完成";
    }

    @GetMapping("/create/book")
    @ResponseBody
    @ApiOperation("生成需要缓存的小说")
    public String createBookFile(){
        //获取所有小说
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD HH:mm:ss");
        List<BookVO> list=bookCacheService.getCacheBookList();
        //循环更新小说
        for (BookVO bookVO:list){
            bookCacheService.createBookFile(bookVO.getId(), bookVO.getBookName());
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                log.info("线程休眠异常");
                e.printStackTrace();
            }
        }
        return sdf.format(new Date())+"缓存执行完成";
    }
}